package com.ofps.forms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.ofps.common.exception.ServiceException;
import com.ofps.forms.common.utils.R;
import com.ofps.forms.common.utils.TokenUtil;
import com.ofps.forms.domain.MyForm;
import com.ofps.forms.mapper.MyFormMapper;
import com.ofps.forms.mapper.QuestionBlankMapper;
import com.ofps.forms.domain.QuestionBlank;
import com.ofps.forms.service.QuestionBlankService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import static com.ofps.common.utils.SecurityUtils.getUserId;


@Service("questionBlankService")
public class QuestionBlankServiceImpl extends ServiceImpl<QuestionBlankMapper, QuestionBlank> implements QuestionBlankService {

    @Resource
    private QuestionBlankMapper questionBlankMapper;
    @Resource
    private MyFormMapper myFormMapper;

    @Override
    public R save(HttpServletRequest request, QuestionBlank questionBlank) {
//        questionBlank.setUserId(TokenUtil.getId(request));
        questionBlank.setUserId(Math.toIntExact(getUserId()));
        return this.save(questionBlank) ? R.ok("创建填空题成功！") : R.error("创建失败！");
    }

    @Override
    public R delete(Map<String, Object> body) {
        QueryWrapper<QuestionBlank> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", body.get("id"));
        return questionBlankMapper.delete(queryWrapper) == 1 ? R.ok("删除成功！") : R.error("删除失败！");
    }

    @Override
    public List<QuestionBlank> SearchQuestionWithQuestionId(String question_id) {
        //返回一个填空题的属性等各项信息
        QueryWrapper<QuestionBlank> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", question_id);
        return questionBlankMapper.selectList(queryWrapper);
    }

    /**
     * 获取表单和问题接口
     * @param jsonObject 请求参数
     * @return 表单和问题数据
     */
    @Override
    public JSONObject getQuestionInfo(JSONObject jsonObject) {
        JSONObject dataJson = new JSONObject();
        String formId = jsonObject.getString("formId");
        QueryWrapper<MyForm> formQueryWrapper = new QueryWrapper<>();
        formQueryWrapper.eq("id", formId);
        MyForm myForm = myFormMapper.selectOne(formQueryWrapper);
        if (myForm == null) {
            throw new ServiceException("formId对应的表单信息不存在~");
        }
        dataJson.put("form", myForm);
        QueryWrapper<QuestionBlank> questionBlankQueryWrapper = new QueryWrapper<>();
        questionBlankQueryWrapper.eq("form_id", myForm.getId());
        questionBlankQueryWrapper.orderByAsc("order_id");
        List<QuestionBlank> questionBlanks = questionBlankMapper.selectList(questionBlankQueryWrapper);
        dataJson.put("questionList", questionBlanks);
        return dataJson;
    }
}
